package com.example.lib_base.base.activity

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aspsine.swipetoloadlayout.OnLoadMoreListener
import com.aspsine.swipetoloadlayout.OnRefreshListener
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.GridSpanSizeLookup
import com.chad.library.adapter.base.module.BaseLoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.drake.statelayout.StateLayout
import com.example.lib_base.R
import com.example.lib_base.base.constant.StateBean
import com.example.lib_base.base.extensions.observeNonNull
import com.example.lib_base.base.http.ApiResponse
import com.example.lib_base.base.util.codes.GsonUtils
import com.example.lib_base.base.vm.BaseRvViewModel
import com.google.gson.JsonParser

abstract class BaseRVActivity<B : ViewDataBinding, VM : BaseRvViewModel, T> :
    BaseAppBVMActivity<B, VM>(), OnRefreshListener, OnLoadMoreListener {
    /**
     * 适配器
     */
    abstract fun createAdapter(): BaseQuickAdapter<T, BaseViewHolder>

    /**
     * 数据源参数类型
     */
    abstract fun createClass(): Class<*>

    /**
     * 获取数据
     */
    abstract fun createListData(page: Int)

    /**
     * 缺省页
     */
//    var multiStateContainer: MultiStateContainer? = null
    var mState: StateLayout? = null

    /**
     * 列表控件
     */
    lateinit var mRecyclerView: RecyclerView

    /**
     * 适配器
     */
    lateinit var mAdapter: BaseQuickAdapter<T, BaseViewHolder>

    /**
     * 刷新控件
     */
    var swipeToLoadLayout: SwipeToLoadLayout? = null

    /**
     * 是否是刷新状态
     */
    var isRefresh = true

    /**
     * 页码
     */
    var page = 1

    override fun initialize(savedInstanceState: Bundle?) {
        initViews()
        initStateLayout()
        mState?.showLoading()
        createListData(page)
    }

    /**
     * 初始化控件
     */
    fun initViews() {
        if (findViewById<RecyclerView>(R.id.swipe_target) != null) {
            mRecyclerView = findViewById(R.id.swipe_target)
        }
        mState = findViewById(R.id.state)

        if (findViewById<SwipeToLoadLayout>(R.id.swipeToLoadLayout) != null) {
            swipeToLoadLayout = findViewById(R.id.swipeToLoadLayout)
            swipeToLoadLayout?.setOnRefreshListener(this)
            swipeToLoadLayout?.setOnLoadMoreListener(this)
            //默认使用自动加载(关闭上拉加载)
            swipeToLoadLayoutSwitch(loadMore = false)
        }
//        initAdapter()
        viewModel.listLiveData.observeNonNull(this) {
            var list = mutableListOf<T>()
            try {
                var arr = JsonParser().parse(it).asJsonArray
                arr.forEach { sub ->
                    var data = GsonUtils.getGson().fromJson(sub, createClass())
                    if (data as T != null) {
                        list.add(data)
                    }
                }
            } catch (t: Throwable) {
                println("--------------- 数据解析异常")
            }
            update(list)
        }
    }

    private fun initStateLayout(){
        mState?.onError {
            if (it is StateBean){
                findViewById<TextView>(R.id.tv_error_msg)?.apply {
                    text = it.message
                }
                findViewById<TextView>(R.id.tv_retry)?.setOnClickListener {
                    onRefresh()
                }
            }
        }

        mState?.onEmpty {
            findViewById<TextView>(R.id.tv_empty_msg)?.apply {
                if (it is StateBean){
                    findViewById<TextView>(R.id.tv_empty_msg)?.apply {
                        text = it.message
                    }
                }
            }
        }
    }


    /**
     * 数据源更新
     */
    open fun update(list: MutableList<T>) {
        println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 数据源更新 $list" )
        when {
            isRefresh && list.size == 0 -> {//第一页无数据 显示缺省页
                showEmptyDataView("暂无数据")
            }
            isRefresh && list.size > 0 -> { //第一页有数据 1、刷新数据 2、显示内容页
                mAdapter.setList(list)
                getLoadMoreModule()?.isEnableLoadMore = true
                showContentView()
            }
            !isRefresh && list.size == 0 -> {//加载页无数据 显示页脚
                mAdapter.addFooterView(layoutInflater.inflate(R.layout.not_loading,
                    mRecyclerView.parent as ViewGroup,
                    false))
//                getLoadMoreModule()?.isAutoLoadMore = false
//                getLoadMoreModule()?.isEnableLoadMore = false
                getLoadMoreModule()?.loadMoreEnd(true)

            }
            !isRefresh && list.size > 0 -> {//加载页有数据 刷新适配器
                mAdapter.addData(list)
                getLoadMoreModule()?.loadMoreComplete()
            }
        }
        //关闭刷新
        swipeToLoadLayout?.isRefreshing = false
        //关闭 加载更多
        swipeToLoadLayout?.isLoadingMore = false
    }

    /**
     * 设置RecyclerView相关配置
     */
    fun initRecyclerView(row: Int = 1, color: Long = 0xffffffff) {
        if (row <= 1) {
            mRecyclerView.layoutManager = LinearLayoutManager(this)
        } else {

            var manager = GridLayoutManager(this, row)
//            manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
//                override fun getSpanSize(position: Int): Int {
//                    return if (position == mAdapter.data.size) row else 1
//                }
//            }
            mRecyclerView.layoutManager = manager

        }
        mRecyclerView.setHasFixedSize(true)
        initAdapter()
    }

    /**
     * 设置Adapter相关配置
     */
    private fun initAdapter() {
        mAdapter = createAdapter()
        try {
            mAdapter.loadMoreModule.isAutoLoadMore = true
            mAdapter.loadMoreModule.preLoadNumber = 5
            mAdapter.loadMoreModule.setOnLoadMoreListener {
                //加载更多逻辑
                onLoadMore()
            }
        } catch (t: Throwable) {
            println("-------------------------  自动加载配置异常 $t")
        }
        mRecyclerView.adapter = mAdapter
        //点击事件
        mAdapter.setOnItemClickListener { adapter, view, position ->

            onRecyclerViewItemClickListener(mAdapter.data[position],position)
        }
        //长按事件
        mAdapter.setOnItemLongClickListener { adapter, view, position ->
            onRecyclerViewItemLongClickListener(mAdapter.data[position],adapter,view,position)
           true
        }
        //子项点击事件
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            OnRecyclerViewChildClickListener(mAdapter.data[position],adapter,view,position)
        }
    }

    /**
     * 列表点击
     */
   open fun onRecyclerViewItemClickListener(bean:T,position:Int){

    }

    /**
     * 列表长按
     */
    open fun onRecyclerViewItemLongClickListener(bean:T,adapter: BaseQuickAdapter<*,*>,view:View,position:Int){

    }

    /**
     *列表子项点击
     */
    open fun OnRecyclerViewChildClickListener(bean:T,adapter: BaseQuickAdapter<*,*>,view:View,position:Int){

    }

    fun getLoadMoreModule(): BaseLoadMoreModule? {
        return try {
            mAdapter.loadMoreModule
        } catch (t: Throwable) {
            null
        }
    }

    override fun <T> serverError(bean: ApiResponse<T>) {
        mState?.showError(StateBean(message = bean.getMsg()))
    }

    override fun <T> networkError(bean: ApiResponse<T>) {
        mState?.showError(StateBean(message = bean.getMsg()))
    }


    /**
     * 错误缺省页
     */
    fun showErrorView(msg:String) {
        mState?.showError(StateBean(message = msg))
    }

    /**
     * 无数据缺省页
     */
    fun showEmptyDataView(msg: String) {
        println("zzzzzzzzzzzzzzzz 无数据缺省页")
        mState?.showEmpty(StateBean(message = msg))
    }

    /**
     * 显示内容页
     */
    fun showContentView() {
       mState?.showContent()
    }

    /**
     * 刷新和加载更多开关
     */
    fun swipeToLoadLayoutSwitch(refresh: Boolean = true, loadMore: Boolean = true) {
        swipeToLoadLayout?.isRefreshEnabled = refresh
        swipeToLoadLayout?.isLoadMoreEnabled = loadMore
    }

    /**
     * 刷新
     */
    override fun onRefresh() {
        mAdapter.removeAllFooterView()
        isRefresh = true
        getLoadMoreModule()?.isEnableLoadMore = false
        page = 1
        createListData(page)
    }

    /**
     * 加载更多
     */
    override fun onLoadMore() {
        isRefresh = false
        page += 1
        createListData(page)
    }
}
